package com.linln.admin.system.controller;

import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.SpringContextUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.excel.ExcelUtil;
import com.linln.component.fileUpload.config.properties.UploadProjectProperties;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.RPatientBaseInfoRepository;
import com.linln.modules.system.repository.RequirementManageRepository;
import com.linln.modules.system.service.RequirementService;
import com.linln.modules.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/requirement/manage")
public class RequirementManageController {
    @Autowired
    private RequirementService requirementService;

    @Autowired
    private UserService ruserService;

    private static final Logger logger = LoggerFactory.getLogger(RequirementManageController.class);

    @GetMapping("/index")
    @RequiresPermissions("requirement:manage:index")
    public String index(Model model, RequirementDetailsEntity rde) {
        RequirementDetailsEntity rerde = new RequirementDetailsEntity();
        if(rde!=null){
            //保持需求状态查询
            rerde.setRequirementStat(rde.getRequirementStat());
            if(rde.getRequirementType()!=null && rde.getRequirementType().equals("4")) {
                rde.setRequirementType(null);
            }
            if(rde.getRequirementStat()!=null && rde.getRequirementStat().equals("4")) {
                rde.setRequirementStat(null);
            }
        }
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("requirementName" ,ExampleMatcher.GenericPropertyMatchers.contains());//全部模糊查询，即%{address}%;

        // 获取日志列表
        Example<RequirementDetailsEntity> example = Example.of(rde, matcher);

        Page<RequirementDetailsEntity> plist = requirementService.getRequireAllList(example);

//        if(plist != null && plist.getContent().size()>0){
//            List<RequirementDetailsEntity> tlist = plist.getContent();
//            for(int i = 0;i<tlist.size();i++){
//                RequirementDetailsEntity tre = tlist.get(i);
//                User tusr = ruserService.getByName(tre.getSubmitUserName());
//                if (tusr !=null){
//                    plist.getContent().get(i).setSubmitUserName(tusr.getNickname());
//                }
//            }
//        }
        // 封装数据
        model.addAttribute("list", plist.getContent());
        model.addAttribute("page", plist);
        model.addAttribute("xqtype",rerde.getRequirementStat());
//        model.addAttribute("dept", user.getDept());
        return "/requirement/manage/index";
    }

    @GetMapping("/add")
    @RequiresPermissions("requirement:manage:add")
    public String toAdd() {
        return "/requirement/manage/add";
    }

    @PostMapping("/save")
    @RequiresPermissions({"requirement:manage:add","requirement:manage:edit"})
    @ResponseBody
    public ResultVo toSave(HttpServletRequest request){

        User user = ShiroUtil.getSubject();
        String tempstring=null;
        String bah = null;
        SimpleDateFormat Dateformatter = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat DateTimeformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.sql.Date dayDateSql = null;
        java.sql.Date outdate = null;
        java.util.Date  curdate = null;
        //患者基本信息
        RequirementDetailsEntity requirementDetailsEntity = null;

        //得到患者ID
        tempstring = request.getParameter("requirementid");
        if (tempstring != null && tempstring.equals("")==false){//根据患者ID查找患者
            requirementDetailsEntity = requirementService.getRequireByID(Integer.parseInt(tempstring));
            if (requirementDetailsEntity==null){
                logger.error("保存需求时，查询失败");
                return ResultVoUtil.error("查询需求失败");
            }
        }

        if(requirementDetailsEntity == null){
            requirementDetailsEntity = new RequirementDetailsEntity();
            //当前用户
            requirementDetailsEntity.setSubmitUserId((int) (long) user.getId());
            requirementDetailsEntity.setSubmitUserName(user.getNickname());

            curdate =new java.util.Date();
            dayDateSql = new java.sql.Date(curdate.getTime());
            requirementDetailsEntity.setSubmitDate(dayDateSql);
//            requirementDetailsEntity.setSubmitDate(user.getUsername());
        }

        //需求名称
        tempstring = request.getParameter("requirementName");
        requirementDetailsEntity.setRequirementName(tempstring);
        //需求类型
        tempstring = request.getParameter("requirementType");
        requirementDetailsEntity.setRequirementType(tempstring);
        //需求状态
        tempstring = request.getParameter("requirementStat");
        requirementDetailsEntity.setRequirementStat(tempstring);
        //需求描述
        tempstring = request.getParameter("requirementDescription");
        requirementDetailsEntity.setRequirementDescription(tempstring);

        //当前用户
        requirementDetailsEntity.setLastModfiyUserId((int) (long) user.getId());
        //最后修改时间
        curdate =new java.util.Date();
        dayDateSql = new java.sql.Date(curdate.getTime());
        requirementDetailsEntity.setLastModfiyDate(dayDateSql);

        //预计完成时间
        tempstring = request.getParameter("expectedCompletionTime");
        if(tempstring != null && tempstring.equals("") == false){
            dayDateSql = new java.sql.Date(Dateformatter.parse(tempstring,new ParsePosition(0)).getTime());
            requirementDetailsEntity.setExpectedCompletionTime(dayDateSql);
        }

        //实际完成时间
        tempstring = request.getParameter("actualCompletionTime");
        if(tempstring != null && tempstring.equals("") == false){
            dayDateSql = new java.sql.Date(Dateformatter.parse(tempstring,new ParsePosition(0)).getTime());
            requirementDetailsEntity.setActualCompletionTime(dayDateSql);
        }

        //备注
        tempstring = request.getParameter("remark");
        requirementDetailsEntity.setRemark(tempstring);

        String [] imagepath = request.getParameterValues("image[]");

        RequirementDetailsEntity rerentity = requirementService.saveRequirementInfo(requirementDetailsEntity);
        if(rerentity != null){
            //删除原来全部图片
            List<RequirementImageEntity> requirementImageEntityList = requirementService.getRequirementImageByRequireid(rerentity.getId());
            if (requirementImageEntityList !=null && requirementImageEntityList.size()>0){
                for(int icur = 0;icur<requirementImageEntityList.size();icur++){
                    requirementService.deleteRequirementImage(requirementImageEntityList.get(icur));
                }
            }

            if(imagepath != null && imagepath.length>0){//保存图片
                for(int i = 0;i<imagepath.length;i++){
                    RequirementImageEntity requirementImageEntity = new RequirementImageEntity();
                    requirementImageEntity.setRequireid(rerentity.getId());
                    requirementImageEntity.setRequireimagepath(imagepath[i]);
                    requirementService.saveRequirementImage(requirementImageEntity);
                }
            }
            return ResultVoUtil.SAVE_SUCCESS;
        }
        return ResultVoUtil.error("保存失败！");
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("requirement:manage:edit")
    public String toEdit(@PathVariable("id") Integer requirementid, Model model) {
        RequirementDetailsEntity requirementDetailsEntity = requirementService.getRequireByID(requirementid);
        //需求信息
        model.addAttribute("requirementinfo",requirementDetailsEntity);

        List<String> imageListPath = new ArrayList<>();

        List<RequirementImageEntity> requirementImageEntityList = requirementService.getRequirementImageByRequireid(requirementid);
        if(requirementImageEntityList != null && requirementImageEntityList.size()>0){
            for(int icur = 0 ;icur<requirementImageEntityList.size();icur++){
                imageListPath.add(requirementImageEntityList.get(icur).getRequireimagepath());
            }
            model.addAttribute("imageList",imageListPath);
            model.addAttribute("imageshow",1);
        }else{
            model.addAttribute("imageList","");
            model.addAttribute("imageshow",0);
        }

        return "/requirement/manage/add";
    }

    @GetMapping("/detail/{id}")
    @RequiresPermissions("requirement:manage:detail")
    public String toDetail(@PathVariable("id") Integer requirementid, Model model) {
        RequirementDetailsEntity requirementDetailsEntity = requirementService.getRequireByID(requirementid);
        //需求信息
        model.addAttribute("requirementinfo",requirementDetailsEntity);

        List<String> imageListPath = new ArrayList<>();

        List<RequirementImageEntity> requirementImageEntityList = requirementService.getRequirementImageByRequireid(requirementid);
        if(requirementImageEntityList != null && requirementImageEntityList.size()>0){
            for(int icur = 0 ;icur<requirementImageEntityList.size();icur++){
                imageListPath.add(requirementImageEntityList.get(icur).getRequireimagepath());
            }
            model.addAttribute("imageList",imageListPath);
            model.addAttribute("imageshow",1);
        }else{
            model.addAttribute("imageList","");
            model.addAttribute("imageshow",0);
        }
        return "/requirement/manage/detail";
    }

    /**
     * 获取用户头像
     */
    @GetMapping("/picture")
    public void picture(String p, HttpServletResponse response) throws IOException {
        String defaultPath = "/images/user-picture.jpg";
        if (p!=null && p.equals("")){
            return;
        }
        if (!(StringUtils.isEmpty(p) || p.equals(defaultPath))) {
            UploadProjectProperties properties = SpringContextUtil.getBean(UploadProjectProperties.class);
            String fuPath = properties.getFilePath();
            String spPath = properties.getStaticPath().replace("*", "");
            File file = new File(fuPath + p.replace(spPath, ""));
            if (file.exists()) {
                FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
                return;
            }
        }
        Resource resource = new ClassPathResource("static" + defaultPath);
        FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
    }

    /**
     * 导出用户数据
     */
    @GetMapping("/export")
    @RequiresPermissions("requirement:manage:export")
    @ResponseBody
    public void exportExcel() {

        RequirementManageRepository requirementManageRepository = SpringContextUtil.getBean(RequirementManageRepository.class);

        List<RequirementDetailsEntity> plist = requirementManageRepository.findAll();
        if(plist != null && plist.size()>0){
            for(int i = 0;i<plist.size();i++){
                RequirementDetailsEntity tre = plist.get(i);

                tre.setId(new Integer(i+1));

                if(tre.getRequirementType().equals("1")){
                    tre.setRequirementType("BUG");
                }
                else if(tre.getRequirementType().equals("2")){
                    tre.setRequirementType("需求");
                }
                else if(tre.getRequirementType().equals("3")){
                    tre.setRequirementType("其他");
                }

                if(tre.getRequirementStat().equals("1")){
                    tre.setRequirementStat("待处理");
                }
                else if(tre.getRequirementStat().equals("2")){
                    tre.setRequirementStat("处理中");
                }
                else if(tre.getRequirementStat().equals("3")){
                    tre.setRequirementStat("已完成");
                }
            }
        }

        ExcelUtil.exportExcel(RequirementDetailsEntity.class, plist);
    }
}
